<?php
namespace control;
class inStockOtherClass extends adIndexClass
{
	private const page        = 'inStockOther';
	private const table       = 'inventory';
	private const tableMx     = 'inventory_detail';
	private const tableRecord = 'inventory_record';
	private const title       = '其他入库单';
	private const state       = ['草稿', '待入库', '已入库'];


	/*列表-查询条件*/
	public function home()
	{
		//生成查询表单
		$html =
			text(["name" => "orderNo", "title" => "单据编号"]) .
			select(['table' => 'subCategory', 'name' => 'subCategory', "title" => "业务类型", 'option' => explode('，', para('inventoryOtherInType')),]) .
            text(array('name' => 'sourceTargetName',"title" => '往来单位', 'id' => 'target')) . hidden(array('name' => 'targetId')).<<<eof
<script>
$("#target").bigAutocomplete({
        url:root + 'control/adIndex.html?cla=inStockExec&fun=getTarget',
        callback:function(data){
            $("[name='targetId']").val(data.id);
        }
    });
</script>
eof.

//            selectMultiple(['option' => self::currentCompany(), "title" => '往来单位', 'name' => 'targetId', 'value' => '']).
			text(['name' => 'orderDate', 'title' => '单据日期~单据日期', 'class' => 'text width200', 'laydate' => ['range' => '~', 'type' => 'date'],]) .
			select(["name" => "state", "title" => "状态", 'option' => self::state]);
		//返回
		return $this->homeFun($this->search($html));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//查询结果
		$where = " coid = '" . self::$coid . "' AND type = '其他入库' AND classify = 1 ";
		$equal = [
			'orderNo'  => $this->post('orderNo'),
			'targetId' => $this->post('targetId'),
		];
		$like  = [
			'subCategory' => $this->post('subCategory'),
			'state'       => $this->post('state'),
		];
		//没有查看所有的权限
//        if (!$this->power(self::page, "seeAll")) {
//             $where .= " and (stid = '" . $this->control['stid'] . "' or auditing like '%".$this->control['stid']."%')";
//        }
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
		}
		$page    = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
		$isPrint = $this->power(self::page, "print") ? true : false;
		//获取表头
		$checkAll = $this->checkAll("listForm", "listId");
		$tr[]     = [$checkAll, '单据编号', '业务类型', '往来单位', '数量', '金额（' . static::$unit . '）', '单据日期', '状态'];
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"    => ["name" => "listId", "value" => $array['id'],],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",],
				"edit"   => ($array['state'] != '已入库') ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')",] : [],
				'print'  => ($isPrint === true) ? ['title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
			];
			$num      = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
			$money    = find(array('table' => self::tableMx, 'single' => "orderId = '$array[id]'", 'field' => " IFNULL(round(sum(num*price),4),0) as money "));
			$target = self::getCompanyName($array['targetId']);
			$tr[]     = [$this->dominate($dominate), $array['orderNo'], $array['subCategory'], $target, self::lostZero($num,'numPrecision'), self::lostZero($money['money']), $array['orderDate'], $array['state']];
		}
		//控件
		$button = "";
		if ($this->power(self::page, "edit")) {
			$button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
		}
		if ($this->power(self::page, "del")) {
			$button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
		}
		if ($this->power(self::page, "print")) {
			$button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
		}

		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' AND type='其他入库' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
		$tr[]     = ['', '物料编码', '物料名称', '规格型号', '单位', '<div class="warehouse">' . '仓库' . self::chooseWarehouse() . '</div>', '批号', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
		$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
		foreach ((array)$result['array'] as $k=>$array) {
			$material    = query('material', " id = '$array[materialId]'");
			$select      = select(['name' => 'unit[]', 'option' => inventoryBalanceClass::materialUnit($array['materialId']), 'value' => $array['unit']]);
			$tr[]        =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this)").
					hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
					hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
					$material['code'],
                    $material['name'],
                    $material['model'],
					$select,
					idSelect(array('name' => 'warehouseId[]', 'sqlForm' => "warehouse WHERE coid = '".self::$coid."' and state = '启用' ".self::getWarehouseSql(), 'change' => 'getInventory', 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库', 'value' => $array['warehouseId'])),
					text(['name' => 'batch[]', 'value' => $array['batch']]),
					text(['name' => 'num[]', 'value' => self::lostZero($array['num'],'numPrecision'), 'blur' => 'countMoney','other' => self::digitalFiltering('numPrecision')]),
					text(['name' => 'price[]', 'value' => self::lostZero($array['price'],'pricePrecision'), 'blur' => 'countMoney','other' => self::digitalFiltering('pricePrecision')]),
					"<span class='total'>0</span>",
					text(['name' => 'mxText[]', 'value' => $array['text'],]),
				];
		}
        $table  = $this->listTable(array('tr' => $tr, 'end' => true));
		$page  = self::page;
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '业务类型' => radio(['name' => "subCategory", 'class' => 'text', 'option' => explode('，', para('inventoryOtherInType')), 'checked' => $info['subCategory']]),
                    '往来单位'         => selectMultiple(['option' => self::currentCompany(), "title" => '往来单位', 'name' => 'targetId', 'value' => $info['targetId']]),
                    must . '单据日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                ],
                [
                    '备注' => text(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '入库明细',
            'button' => "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())\">选择物料</span>",
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<efo
<script>
//计算金额，税额等
function countMoney(e){
    let obj = $(e).parent().parent()
    let num = obj.find('[name="num[]"]').val(),
        price = obj.find('[name="price[]"]').val()
    let total = num * price
    obj.find(".total").html(total.toFixed(amountPrecision))
}

function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}

function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name="+name+"]").val(val);
}
</script>

efo;
		//返回
		return $this->tab($data);
	}

    /**
     * 获取往来单位
     *
     * @return array
     */
    final public static function  currentCompany(): array
    {
        $res = self::sqlFind(" select khid as id,concat(orderNo,'-',companyName) as name from kehu where coid = '".self::$coid."' UNION ALL select id,concat(code,'-',name) as name from supplier where coid = '".self::$coid."' ");
        return array_column($res,'name','id');
    }

    /**获取往来单位名称
     * @param string $targetId
     * @return string
     */
    final public static function  getCompanyName($targetId=''): string
    {
        $target = '';
        if($targetId) {
            $target = query('kehu', " khid = '$targetId' ")['companyName'];
            if (empty($target)) {
                $target = query('supplier', " id = '$targetId' ")['name'];
            }
        }
        return $target;
    }


    /**
	 * 选择仓库
	 *
	 * @return string
	 */
	public static function chooseWarehouse(string $obj = ''): string
	{
		$obj    = $obj ?: 'warehouseId';
		$result = find(array('table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ".self::getWarehouseSql()." order by time desc"));
		$li     = '';
		if (is_array($result['array'])) {
			foreach ($result['array'] as $array) {
				$li .= "<li data-id='$array[id]'>{$array['name']}</li>";
			}
		}
		if (empty($li)) {
			$li = "<li>未找到仓库</li>";
		}
		return <<<EOT
        <span class='del-row-button' id='chooseWareHouse'>批量</span><div class='stateBlock' style="margin-top: 7px;"><ul>$li</ul></div>
        <script>
         //点击非下拉区域隐藏
        $(document).bind('click', function (e) {
            let target = $(".stateBlock");
            let obj = $(".warehouse");
            if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
              target.hide();
            }
        });
        $("#chooseWareHouse").on('click',function() {
           $(".stateBlock").show();
        })
        $(".warehouse .stateBlock li").on('click',function() {
            let id = $(this).data('id');
            $("select[name='{$obj}[]']").each(function() {
              let obj = $(this);
              obj.val(id);
            });
           $(".stateBlock").hide();
        })
        </script>    
EOT;
	}

	public function editEdit()
	{
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr = $this->post('materialId');
		$unitArr          = $this->post('unit');
		$batchArr         = $this->post('batch');
		$numArr           = $this->post('num');
		$priceArr         = $this->post('price');
		$mxTextArr        = $this->post('mxText');
		$warehouseArr     = $this->post('warehouseId');
		$field            = [
			'subCategory' => $this->post('subCategory'),
			'targetId'    => $this->post('targetId'),
			'orderDate'   => $this->post('orderDate'),
			'text'        => $this->post('text'),
		];
		$annotation       = [
			'subCategory' => '业务类型',
			'targetId'    => '往来单位',
			'orderDate'   => '单据日期',
			'text'        => '备注',
		];
		$rules            = [
			'subCategory' => 'required',
			// 'targetId' => 'required',
			'orderDate'   => 'required|date',
			// 'type'           => 'required',
			// 'text'           => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '请选择入库明细';
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = '请选择入库明细';
		} elseif (static::is_null_array($numArr)) {
			$json['warn'] = '数量请填写完整';
		} elseif (static::is_null_array($priceArr)) {
			$json['warn'] = '单价请填写完整';
		} elseif (static::is_null_array($unitArr)) {
			$json['warn'] = '请选择主单位';
		} elseif (static::is_null_array($warehouseArr)) {
			$json['warn'] = '请选择入库仓库';
		} elseif (!empty($info['id']) && $info['state'] == '已入库') {
			$json['warn'] = '此入库单已入库，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'QTRK' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'          => $id,
					'orderNo'     => $orderNo,
					'type'        => '其他入库',
					'classify'    => 1,
					'warehouseId' => '0000',
					'state'       => '草稿',
					'coid'        => self::$coid,
					'stid'        => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(self::tableMx, "id = '$nid'");
                    //检查物料的入库批次是否使用过
                    $material  = query("material", " id = '" . $materialIdArr[$k] . "' ","id,name,isBatch");
                    $warn = ($material['isBatch'] == 1 && empty($batchArr[$k]))?"物料【".$material['name']."】必须管理批号":inStockClass::batchCheck($material['id'],[$batchArr[$k]]);
                    if($warn !== true){
                        $json['warn'] = $warn;
                        break;
                    }
                    $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                    $priceArr[$k] = self::formattingFigure($priceArr[$k],'pricePrecision');
					if (!empty($mx['id'])) {
						//更新
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'materialId'    => $materialIdArr[$k],
								'batch'         => $batchArr[$k],
								'num'           => $numArr[$k],
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'warehouseId'   => $warehouseArr[$k],
								'money'         => self::formattingFigure($numArr[$k] * $priceArr[$k]),
								'text'          => $mxTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'            => $nid,
								'coid'          => self::$coid,
								'orderId'       => $id,
                                'materialId'    => $materialIdArr[$k],
                                'batch'         => $batchArr[$k],
								'num'           => $numArr[$k],
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'warehouseId'   => $warehouseArr[$k],
								'money'         => self::formattingFigure($numArr[$k] * $priceArr[$k]),
								'text'          => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


    /**
     * @return string
     */
	public function addMx(): string
	{
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(['name' => 'targetId', 'value' => $this->post('targetId')]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$tr = [];
            //是否自动生成批号
            //物料档案管理批号，并且公共设置批号自动生成，并且自动带出批号
            $inventorySetting = optionSettingClass::getSetting('库存');
            $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
            $batchCtrl = $optionSetting['batchCtrl'];
			foreach ($mxIdArr as $mxId) {
				$material     = query('material', "id = '$mxId'");
                if(!empty($material['isBatch']) && $batchCtrl['auto'] && $inventorySetting['autoBatch']['option']) {
                    $batch = inStockClass::getBatchNo('其他入库', $this->post('targetId'));
                }else{
                    $batch = "";
                }
				$id           = self::getId();
				$select       = select(['name' => 'unit[]','value' => $material['unit'], 'option' => inventoryBalanceClass::materialUnit($material['id'])]);
				$warehouseSel = idSelect(array('name' => 'warehouseId[]', 'sqlForm' => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' ".self::getWarehouseSql(), 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库',));
                $price = inventoryDefaultClass::pricingRules('inStockPrice',$material['id']);

                $tr[]        =
                    [
                        componentClass::tablePperation('',"delTableRow(this)").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $mxId]),
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $select,
                        $warehouseSel,
                        text(['name' => 'batch[]', 'value' => $batch]),
                        text(['name' => 'num[]', 'value' => '', 'blur' => 'countMoney','other' => self::digitalFiltering('numPrecision')]),
                        text(['name' => 'price[]', 'value' => $price, 'blur' => 'countMoney','other' => self::digitalFiltering('pricePrecision')]),
                        "<span class='total'>0</span>",
                        text(['name' => 'mxText[]', 'value' => '']),
                    ];
			}
			$json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
		}
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}' AND type = '其他入库' ");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已入库') {
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
						'style' => 'li-btn-blue-bg',
					];
					//按钮
					$button[] = [
						"name" => "提交",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待入库') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待入库') {
				$button[] = [
					"name" => "取消",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			//操作记录
			$result = find(array('table' => 'auditing_follow', 'where' => "typeId = '$info[id]' order by time desc"));
			$li     = '';
			if (is_array($result['array'])) {
				foreach ($result['array'] as $array) {
					$li .= "<li>{$array['text']}&emsp;{$array['time']}</li>";
				}
			}
			if (empty($li)) {
				$li = "<li>暂无记录</li>";
			}
			$mxtr[] = ['物料编码', '物料名称', '规格型号', '单位', '仓库', '批号', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$warehouse   = query('warehouse', " id = '$array[warehouseId]' ");
				$mxtr[]      = [
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
					$warehouse['name'],
					$array['batch'],
					self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($array['price'],'pricePrecision'),
					self::formattingFigure($array['num'] * $array['price']),
					$array['text'],
				];
			}
			$res      = find([
			    'table' => self::tableMx,
                'field' => "IFNULL(sum(num), 0) as num, IFNULL(sum(num*price),0) as total",
                'single' => "orderId = '$info[id]' group by orderId"
            ]);
			//生成表单
			$data['html'] = $this->tableShow([
				"button" => $button,
				[
					[
						"业务类型" => $info['subCategory'],
						"往来单位"  => self::getCompanyName($info['targetId']),
						"单据日期" => $info['orderDate'],
					],
					[
						"备注" => $info['text'],
					],
					[
						"单据编号" => $info['orderNo'],
						"制单人"  => self::findStaff($info['stid']),
						"状态"   => $info['state'] . "&emsp;<span class='del-row-button' id='record'>操作记录<div class='stateBlock operate-content'><ul>$li</ul></div></span>",
					],
				],
				'入库明细'   => [
					[
						"<div style='color: grey;float: right;margin-right: 20px'>数量合计：" . (!empty($res['num']) ? self::lostZero($res['num'],'numPrecision') : 0) . "，金额合计：" . (!empty($res['total']) ? self::lostZero($res['total']) : 0) . "</div>" . $this->tableMany(['tr' => $mxtr]),
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state' => '已入库',
			// 'checkId'     => self::$stid,
			// 'confirmTime' => $this->time
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此其他入库单';
		} elseif ($info['state'] != '待入库') {
			$json['warn'] = '此申请单不是待入库状态，不能确认';
		} else {
			$this->startTrans();
			$isPass = true; // 事务通过标志

			$json['warn'] = update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
				$details = find([
					'table' => self::tableMx,
					'where' => " orderId = '{$info['id']}'",
				]);
				foreach ($details['array'] as $key => $value) {
				    //检查物料的入库批次是否使用过
				    $warn = inStockClass::batchCheck($value['materialId'],[$value['batch']]);
				    if($warn !== true){
				        $json['warn'] = $warn;
                        goto resp;
                    }
                    // 转换主单位
                    $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                    $warn = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "top");  //最高库存控制
                    if($warn !== true){
                        $json['warn'] = $warn;
                        goto resp;
                    }
                    $material = query("material"," id = '".$value['materialId']."' ");
                    if(empty($material['positionId']) || $material['warehouse'] != $value['warehouseId']) {
                        $material['positionId'] = inventoryBalanceClass::matchLocation($value['warehouseId']);
                        $material['warehouse'] = $value['warehouseId'];
                    }
                    //单位单价转换
                    $price = round((float)$value['num']*(float)$value['price']/(float)$mainUnitNum,4);
                    inventoryDefaultClass::recordInventoryPrice($value['materialId'],$mainUnitNum,$price);//计算记录加权平均单价
                    $recordId = self::getNo();
					static::insert([
						'table' => self::tableRecord,
						'field' => [
							'id'            => $recordId,
							'coid'          => self::$coid,
							'warehouseId'   => $material['warehouse'],
                            'positionId' => $material['positionId'],
							'materialId'    => $value['materialId'],
                            'batch' => $value['batch'],
							'num'           => $mainUnitNum,
                            'inventoryId' => $info['id'],
                            'inventoryMxId' => $value['id'],
						],
					]);
                    if(!empty($material['positionId']))inventoryBalanceClass::recordStockToLocation($recordId,['positionId'=>$material['positionId']]);

				}
				$this->commitTrans();//提交事务
				auditingFollow(array(
					"type"   => "其他入库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 取消
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '草稿',
			//'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有取消权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此其他入库单';
		} /* elseif ($info['state'] != '已确认') {
            $json['warn'] = '此报价单不是已确认状态，无需撤回';
        } elseif(static::total(['table'=>'purchase_order_detail','where'=>"sourceId in (select id from ".self::tableMx." where orderId = '$id') and coid = '".self::$coid."'"]) >0){
            $json['warn'] = '此申请单已在采购单中使用，暂不能撤回';
        }*/
		else {
			$json['warn'] = update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow(array(
					"type"   => "其他入库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】取消",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state' => '待入库',
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此其他入库单';
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = '此报价单不是草稿状态，不能提交';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "其他入库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】提交",
				]);

				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act = $this->post('act') ?? '';
		$pwd = $word = false; // 需要密码
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否确认此其他入库单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此其他入库单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认取消此其他入库单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已入库') {
					$warn = "删除失败：已入库，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
		$info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称
		$info['title']       = self::title;
		$info['printTime']   = $this->time;
		$info['stid']        = self::findStaff($info['stid']);
		$info['sorderNo']    = $info['sourceTable'] ? query($info['sourceTable'], " id = '{$info['sourceId']}' ")['orderNo'] : '';
		$info['warehouseId'] = query('warehouse', "id = '$info[warehouseId]'")['name'];
        $info['targetId'] = self::getCompanyName($info['targetId']);
		$info['qr']        = 'source=' . self::page . 'Other&id=' . $info['id'];
		$info['orderDate'] = date('Y/m/d', strtotime($info['orderDate']) ?: strtotime($info['time']));
		$detail            = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
		$items             = [];
		$x                 = 1;
		$totalNum          = $totalMoney = 0;
		foreach ($detail as $array) {
			$material    = query('material', "id = '$array[materialId]'");
			$warehouse   = query('warehouse', "id = '$array[warehouseId]'");
			$items[]     = [
				'no'              => $x,
				'materialCode'    => $material['code'],
				'materialName'    => $material['name'],
				'warehouse'       => $warehouse['name'],
				'model'           => $material['model'],
				'unit'            => $material['unit'],
				'batch'           => $array['batch'],
				'num'             => self::lostZero($array['num'],'numPrecision'),
				'price'           => self::lostZero($array['price'],'pricePrecision'),
				'money'           => self::lostZero($array['money']),
				'text'            => $array['text'],
			];
			$x++;
			$totalMoney += floatval($array['money']);
			$totalNum   += floatval($array['num']);
		}
		$append         = [
			'no'    => '合计',
			'num'   => self::lostZero($totalNum,'numPrecision'),
			'money' => self::lostZero($totalMoney),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

}
